import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'


const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  email: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    avatar = process.env.VUE_APP_FILE_API + '/file/' + avatar
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_Email: (state, email) => {
    state.email = email
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { u_id, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ u_id: u_id.trim(), password: password  }).then(response => {
        const data = response
        sessionStorage.setItem('psdData',JSON.stringify(data))
        // 存储token 放到cookie里 方便保存
        commit('SET_TOKEN', data.data.token)
        setToken(data.data.token)
        // 存储用户类型到cookie 日志监听
        let oDate=new Date();
        oDate.setDate(oDate.getDate()+360);
        document.cookie='type='+data.data.type+"; expires="+oDate.toDateString();
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data,other } = response
        // 存储权限和个人数据 这部分存到sessionStroge
        sessionStorage.setItem('psdRoles',JSON.stringify(other))
        sessionStorage.setItem('psdPersonData',JSON.stringify(data))
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        // 权限必须是数组
        var roles = JSON.parse(sessionStorage.getItem('psdRoles'))
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', data.username)
        commit('SET_AVATAR', data.head)
        commit('SET_Email', data.email)
        // commit('SET_INTRODUCTION', introduction)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        let oDate=new Date();
        oDate.setDate(oDate.getDate()-1);
        document.cookie='type='+''+"; expires="+oDate.toDateString();
        sessionStorage.clear()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // // dynamically modify permissions
  // async changeRoles({ commit, dispatch }, role) {
  //   const token = role + '-token'

  //   commit('SET_TOKEN', token)
  //   setToken(token)

  //   const { roles } = await dispatch('getInfo')

  //   resetRouter()

  //   // generate accessible routes map based on roles
  //   const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
  //   // dynamically add accessible routes
  //   router.addRoutes(accessRoutes)

  //   // reset visited views and cached views
  //   dispatch('tagsView/delAllViews', null, { root: true })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
